package ua.edu.nuos.jeetraining2012.automator.process.mgmt.dao;

import ua.edu.nuos.jeetraining2012.automator.process.mgmt.vo.ProcessEntity;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 * JEE Training 2012-2013.
 *
 * @author Alexandr Dibrivny
 *         Date: 04.06.13
 *         Time: 19:50
 */
public class ProcessDAO {
    private final String PERSISTENCE_UNIT_NAME = "ProcessUnit";
    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;

    public ProcessDAO() {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        entityManager = entityManagerFactory.createEntityManager();
    }

    public void insertProcess(ProcessEntity processesVO) {
        this.persist(processesVO);
    }

    public void deleteProcess(ProcessEntity processesVO) {
        this.remove(processesVO);
    }

    public ProcessEntity selectProcess(ProcessEntity processesVO) {
        return this.select(processesVO);
    }

    public void updateProcess(ProcessEntity processesVO) {
        this.merge(processesVO);
    }

    private void merge(ProcessEntity processesVO) {
        entityManager.getTransaction();
        entityManager.merge(processesVO);
        entityManager.getTransaction().commit();
    }

    private void persist(ProcessEntity processesVO) {
        entityManager.getTransaction();
        entityManager.merge(processesVO);
        entityManager.getTransaction().begin();
    }

    private void remove(ProcessEntity processesVO) {
        entityManager.getTransaction();
        entityManager.remove(processesVO);
        entityManager.getTransaction().commit();
    }

    private ProcessEntity select(ProcessEntity processesVO) {
        ProcessEntity selectProcess;
        final String SQL = "select * from processes where id = ?";
        Query select = entityManager.createNamedQuery(SQL);
        select.setParameter(1, processesVO.getId());
        selectProcess = (ProcessEntity) select.getSingleResult();
        return selectProcess;
    }
}
